package jwf.fcgi;

import java.io.BufferedInputStream;
import java.io.IOException;

public class FCGXHeader {
    public byte version;
    public byte type;
    public byte requestIdB1;
    public byte requestIdB0;
    public byte contentLengthB1;
    public byte contentLengthB0;
    public byte paddingLength;
    public byte reserved;

    public static FCGXHeader readHeader(BufferedInputStream in)
	    throws IOException {
	byte[] headerBuff = new byte[FCGXConstants.FCGIHeaderLen];
	if (in.available() == 0) {
	    return null;
	}
	int l = in.read(headerBuff, 0, FCGXConstants.FCGIHeaderLen);
	if (l != FCGXConstants.FCGIHeaderLen) {
	    return null;
	}
	FCGXHeader header = new FCGXHeader();
	header.version = headerBuff[0];
	header.type = headerBuff[1];
	header.requestIdB1 = headerBuff[2];
	header.requestIdB0 = headerBuff[3];
	header.contentLengthB1 = headerBuff[4];
	header.contentLengthB0 = headerBuff[5];
	header.paddingLength = headerBuff[6];
	header.reserved = headerBuff[7];
	return header;
    }

    public static byte[] makeHeader(int type, int requestId, int contentLen,
	    int paddingLen, int rev) {
	byte[] header = new byte[FCGXConstants.FCGIHeaderLen];
	header[0] = (byte) FCGXConstants.FCGIVersion1;
	header[1] = (byte) type;
	header[2] = (byte) ((requestId >> 8) & 0xff);
	header[3] = (byte) ((requestId) & 0xff);
	header[4] = (byte) ((contentLen >> 8) & 0xff);
	header[5] = (byte) ((contentLen) & 0xff);
	header[6] = (byte) paddingLen;
	header[7] = (byte) rev; // reserved byte
	return header;
    }

    public int getRequestId() {
	return ((requestIdB1 & 0xFF) << 8) + (requestIdB0 & 0xFF);
    }

    public int getContentLength() {
	return ((contentLengthB1 & 0xFF) << 8) + (contentLengthB0 & 0xFF);
    }

    public int getPaddingLength() {
	return (paddingLength & 0xFF);
    }

    public int getType() {
	return (type & 0xFF);
    }

    public String toString() {
	StringBuffer sb = new StringBuffer();
	sb.append("version:").append(version).append("\t");
	sb.append("type:").append(type).append("\t");
	sb.append("requestIdB1:").append(requestIdB1).append("\t");
	sb.append("requestIdB0:").append(requestIdB0).append("\t");
	sb.append("contentLengthB1:").append(contentLengthB1).append("\t");
	sb.append("contentLengthB0:").append(contentLengthB0).append("\t");
	sb.append("paddingLength:").append(paddingLength).append("\t");
	sb.append("reserved:").append(reserved);
	return sb.toString();
    }

}
